package com.zsy.petshop_01.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zsy.petshop_01.common.result.ResponseResult;
import com.zsy.petshop_01.dao.mapper.OrderMessageMapper;
import com.zsy.petshop_01.model.entity.OrderMessage;
import com.zsy.petshop_01.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

@Component
public class OrderMessageManager {
    @Autowired
    OrderMessageMapper orderMessageMapper;
    @Autowired
    AlipayService alipayService;

    public void insert(OrderMessage orderMessage) {
        orderMessageMapper.insert(orderMessage);
    }

    public IPage<OrderMessage> selectPage(IPage<OrderMessage> page, Integer userId, String time, Boolean isDispose, Boolean isAccomplish) {
        LambdaQueryWrapper<OrderMessage> wrapper = new LambdaQueryWrapper<>();
        if (userId != null)
            wrapper.eq(OrderMessage::getUserId, userId);
        if (time != null) {
            long timestamp = Long.parseLong(time);
            Date date = new Date(timestamp);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 设置为当天 0 点
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date startOfDayDate = calendar.getTime();
            long startOfDayTimestamp = startOfDayDate.getTime(); // 获取当天 0 点的时间戳

            // 设置为当天 24 点（实际是第二天 0 点）
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date endOfDayDate = calendar.getTime();
            long endOfDayTimestamp = endOfDayDate.getTime(); // 获取第二天 0 点的时间戳

            wrapper.between(OrderMessage::getCreateTime, startOfDayTimestamp, endOfDayTimestamp);
        }
        if (isDispose != null)
            wrapper.eq(OrderMessage::getIsDispose, isDispose);
        if (isAccomplish != null)
            wrapper.eq(OrderMessage::getIsAccomplish, isAccomplish);

        return orderMessageMapper.selectPage(page, wrapper);
    }

    public void disposeOrder(Integer id) {
        LambdaUpdateWrapper<OrderMessage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderMessage::getId, id)
                .set(OrderMessage::getIsDispose, true);
        orderMessageMapper.update(null, wrapper);
    }

    public void accomplishOrder(Integer id) {
        LambdaUpdateWrapper<OrderMessage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderMessage::getId, id)
                .set(OrderMessage::getIsAccomplish, true);
        orderMessageMapper.update(null, wrapper);
    }

    public ResponseResult<?> cancelOrder(Integer id, String reason) {
        OrderMessage orderMessage = orderMessageMapper.selectById(id);
        ResponseResult<?> result = new ResponseResult<>();
        if (orderMessage.getIsAccomplish()) {
            return ResponseResult.fail("订单已完成，无法直接退款");
        }
        //退钱
        try {
            result = alipayService.refund(orderMessage.getOrderId(), orderMessage.getPrice().toString(), reason);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result.getSuccess()) {
            //删除该订单
            orderMessage.setIsRefund(true);
            orderMessage.setRefundReason(reason);
            orderMessageMapper.updateById(orderMessage);
            return ResponseResult.success("取消成功");
        } else {
            return ResponseResult.fail(result.getMessage());
        }
    }
}
